package org.piera.diables;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import org.apache.http.util.ByteArrayBuffer;

import android.os.Environment;

public class Storage {

    private static final String DNAME = "diablesdepiera";
    
    public void saveImage(InputStream image, String fileName){
    	//Create a new directory on external storage
        File rootPath = new File(Environment.getExternalStorageDirectory(), DNAME);
        if(!rootPath.exists()) {
            rootPath.mkdirs();
        }
        //Create the file reference
        File dataFile = new File(rootPath, fileName);
        
        //Check if external storage is usable
        if(!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            //Toast.makeText(this, "Cannot use storage.", Toast.LENGTH_SHORT).show();
            //finish();
            return;
        }
        
        //Create a new file and write some data
        try {           
            /*FileOutputStream mOutput = new FileOutputStream(dataFile, false);
            String data = text;
            mOutput.write(data.getBytes());
            mOutput.close();*/
        	BufferedInputStream bis = new BufferedInputStream(image);
        	/*
        	* Read bytes to the Buffer until there is nothing more to read(-1).
        	 */
        	ByteArrayBuffer baf = new ByteArrayBuffer(50);
        	int current = 0;
        	while ((current = bis.read()) != -1) {
        	         baf.append((byte) current);
        	}
        	
        	FileOutputStream fos = new FileOutputStream(dataFile,false);
        	fos.write(baf.toByteArray());
        	fos.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    	
    }
    
}
